package com.robaone.gwt.hierarcialdb.client.ui.menu;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;
import com.robaone.gwt.hierarcialdb.client.ListItem;
import com.robaone.gwt.hierarcialdb.client.OrderedList;
import com.robaone.gwt.hierarcialdb.client.state.AdminState;
import com.robaone.gwt.hierarcialdb.client.state.StartState;

public class MenuUi extends Composite{
	private ListItem[] items = null;
	
	private static MenuUiUiBinder uiBinder = GWT.create(MenuUiUiBinder.class);
	private boolean initialized = false;
	interface MenuUiUiBinder extends UiBinder<Widget, MenuUi> {
	}
	
	public MenuUi() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField OrderedList menu;

	public boolean isInitialized() {
		return initialized;
	}
	
	public void setInitialized(boolean b){
		this.initialized = b;
	}

	public OrderedList getOrderedList() {
		return menu;
	}

	public void setItems(final String[] result) throws Exception {
		items = new ListItem[result.length];
		for(int i = 0; i < result.length;i++){
			ListItem item = new ListItem();
			items[i] = item;
			Anchor a = new Anchor(result[i]);
			final int index = i;
			a.addClickHandler(new ClickHandler(){

				@Override
				public void onClick(ClickEvent event) {
					MenuUi.this.setActiveItem(index);
					if(result[index].equalsIgnoreCase("home")){
						StartState.go();
					}else if(result[index].equalsIgnoreCase("admin")){
						AdminState.go();
					}
				}
				
			});
			item.add(a);
			menu.add(item);
		}
		this.setActiveItem(0);
		this.setInitialized(true);
	}

	public void setActiveItem(int i) {
		if(this.items != null && this.items.length > i){
			this.items[i].addStyleName("current_page_item");
			for(int in = 0; in < this.items.length;in++){
				if(in == i) continue;
				this.items[in].removeStyleName("current_page_item");
			}
		}
	}
}
